package br.indt.framework.scheduler;

/**
 *
 * @author efirmino
 */
public class Scheduler {
    private final JobQueue queue;
    private final Timer timer;

    public Scheduler() {
        queue = new JobQueue();

        timer = new Timer(queue);
        timer.start();
    }

    public void add(Task t, int delaySeconds) {
        add(t, delaySeconds, false);
    }

    public void add(Task task, int delaySeconds, boolean periodic) {
        checkArgs(task, delaySeconds);
        Job job = new Job(task, delaySeconds, periodic);

        queue.add(job);
        notifyQueueChange();
    }

    public void remove(Task t) {
        queue.remove(t);
        notifyQueueChange();
    }

    public void removeAll() {
        if (!queue.isEmpty()) {
            queue.removeAll();
            notifyQueueChange();
        }
    }


    private void checkArgs(Task t, long delaySeconds)
            throws IllegalArgumentException, NullPointerException {
        if (t == null) {
            throw new NullPointerException("Task t is null");
        }

        if (delaySeconds < 0) {
            String message = "delaySeconds is negative, ";
            message += "must be greater or equal than zero";

            throw new IllegalArgumentException(message);
        }
    }

    private void notifyQueueChange() {
        synchronized (timer) {
            timer.notify();
        }
    }

    public boolean isEmpty() {
        return queue.isEmpty();
    }
}
